package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;

/**
 * 机构管理 服务实现
 *
 * @author ruoyi
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询医院列表
     *
     * @param districtsId 地区编号
     * @param hospList    查询区县地址类型列表
     * @return
     */
    @Override
    public List<SysDept> selectHospList(Integer districtsId, String[] hospList) {
        return deptMapper.selectHospList(districtsId, hospList);
    }

    // 根据用户所在的deptId查询暂存点id
    @Override
    public List<Long> getStagingIdByHospitalId(Long hospitalId) {
        return deptMapper.getStagingIdByHospitalId(hospitalId);
    }

    // 根据登录名(医院管理员)获取暂存点id（多个暂存点id用、隔开）
    @Override
    public List<SysDept> getStagingIdByLoginName(String loginName) {
        return deptMapper.getStagingIdByLoginName(loginName);
    }

    // 根据机构id查询机构下医废数目
    @Override
    public int selectYFCountByDeptId(Long deptId) {
        return deptMapper.selectYFCountByDeptId(deptId);
    }

    // 根据机构id查询机构下科室数目
    @Override
    public int selectKSCountByDeptId(Long deptId) {
        return deptMapper.selectKSCountByDeptId(deptId);
    }

    // 根据地区查找对应的卫健局
    @Override
    public SysDept getWJJDeptBydisId(Long disId) {
        return deptMapper.getWJJDeptBydisId(disId);
    }

    @Override
    public List<SysDept> selectHospitalInfo(Long componyId) {
        //根据处置公司id查询负责的医院id
        List<Long> hospitalIds = deptMapper.selectHospitalByComponyId(componyId);
        //根据医院id的列表查询医院信息返回
        List<SysDept> depts =  deptMapper.selectHospitalsByIds(hospitalIds);
        return depts;
    }

    @Override
    public List<SysDept> selectHospitalAll() {
        return deptMapper.selectHospitalAll();
    }

    /**
     * XiaoYi...
     * 获取所有医院列表
     * @Date : 2020-03-11 15:48
     */
    @Override
    public List<SysDept> selectHospital(Long deptIds) {
        return deptMapper.selectHospital(deptIds);
    }


    /**
     * 获取本机构下未签署三方医废处理的医院机构
     * @param deptIds
     * @return
     */
    public List<SysDept> selectMedicalWasteHospitals(Long currentDeptId,Long deptIds) {
        return deptMapper.selectMedicalWasteHospitals(currentDeptId,deptIds);
    }



    public SysDept selectCurrentDept(Long deptid){
        return  deptMapper.selectCurrentDept(deptid);
    }

    /**
     * 查询机构管理数据
     *
     * @param dept 机构信息
     * @return 机构信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }


    /**
     * 查询医院管理数据
     *
     * @param dept 机构信息
     * @return 机构信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectHospitalList(SysDept dept) {
        return deptMapper.selectHospitalList(dept);
    }

    /**
     * 查询机构管理树
     *
     * @param dept 机构信息
     * @return 所有机构信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTree(SysDept dept) {
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 根据角色ID查询机构（数据权限）
     *
     * @param role 角色对象
     * @return 机构列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = selectDeptList(new SysDept());
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }


    /**
     * 加载机构列表树(更新app的机构)
     */
    @Override
    public List<Ztree> updateRegionDeptTreeData(String updateRegion) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = selectDeptList(new SysDept());
        if (!StringUtils.isEmpty(updateRegion)) {
            String[] regionZu = updateRegion.split(",");
            List<String> regionList = Arrays.asList(regionZu);
            List<String> deptIdNameList = deptMapper.selectDeptTreeByIds(regionList);
            ztrees = initZtree(deptList, deptIdNameList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }


    /**
     * 对象转机构树
     *
     * @param deptList 机构列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转机构树
     *
     * @param deptList     机构列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (SysDept dept : deptList) {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                ztree.setType(dept.getDeptType());
                if (isCheck) {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询机构人数
     *
     * @param parentId 机构ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        SysDept dept = new SysDept();
        dept.setParentId(parentId);
        return deptMapper.selectDeptCount(dept);
    }

    /**
     * 查询机构是否存在用户
     *
     * @param deptId 机构ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        try{
            int result = deptMapper.checkDeptExistUser(deptId);
            return result > 0 ? true : false;
        } catch (Exception e) {
            throw new BusinessException("查询机构失败！");
        }
    }

    /**
     * 删除机构管理信息
     *
     * @param deptId 机构ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 新增保存机构信息
     *
     * @param dept 机构信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("机构停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存机构信息
     *
     * @param dept 机构信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该机构是启用状态，则启用该机构的所有上级机构
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该机构的父级机构状态
     *
     * @param dept 当前机构
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的机构ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 根据机构ID查询信息
     *
     * @param deptId 机构ID
     * @return 机构信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 校验机构名称是否唯一
     *
     * @param dept 机构信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }


}
